<?php

/**
* ClassLoader
*/
class ClassLoader
{
  protected static $_instance;
  public static function getInstance(){
    if(self::$_instance==null){
      self::$_instance= new ClassLoader();
    }
    return self::$_instance;
  }
    
  protected $_classPathArray;
  
  protected function __construct()
  {
    $this->_classPathArray = array();
    $this->addClassPath(realpath(dirname(__FILE__).'../../../'));
    //var_dump($this->_classPathArray);
  }
  
  public function addClassPath($classPath){
    if(!in_array($classPath,$this->_classPathArray)){
      $this->_classPathArray[] = $classPath;
    }
  }
  
  public function load($uri){
    foreach ($this->_classPathArray as $path) {
      if($this->_load($path,$uri)){
        return;
      }
    }
    throw new Exception('class '.$uri.' not found!');
  }
  
  protected function _load($classPath,$classUri){
    $className = $this->guessClassName($classUri);
    
    if($className=='*'){
      return $this->_loadDir($classPath,$classUri);
    }else{
      return $this->_loadClass($classPath,$classUri);
    }
    
    return false;
  }
  
  protected function _loadDir($classPath,$classUri){
    $dirName = str_replace('.','/',$classUri);
    $dirName = realpath($classPath.'/'.substr($dirName,0,strlen($dirName)-2));
    
    if(is_dir($dirName)){
          
      $direcrory = dir($dirName);
      
      while (false !== $class=$direcrory->read()) {
        if($class !=' .' && $class != '..'){
          if(str_replace('.class.php','',$class)!=$class){
          
            $className = str_replace('.class.php','',$class);
            $uri = str_replace('*',$className,$classUri);
            try{
              $this->_loadClass($classPath,$uri);
            }catch(Exception $e){}
            
          }// end if
        }// end if
      } // end while
    } //end if
    
    return true;
  }
  
  
  
  protected function _loadClass($classPath,$classUri){
    $className = $this->guessClassName($classUri);
    
    $realPath = $classPath.'/'.str_replace('.','/',$classUri).'.class.php';
    
    if(file_exists($realPath)){
      
      include_once($realPath);
      
      if((!class_exists($className))&&(!interface_exists($className))){
        return false;
      }
      
      return true;
    }
      
    return false;
  }
  
  public function guessClassName($uri){
    $uriArray = explode('.',$uri);
    
    $className = $uriArray[sizeof($uriArray)-1];
    
    return $className;
  }
  
}

function import($uri){
  ClassLoader::getInstance()->load($uri);
}

?>